package sf.database.template.freemarker.ext;

import freemarker.core.Environment;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import sf.database.template.TemplateConstants;
import sf.database.template.freemarker.FreemarkerHelp;
import sf.spring.util.CollectionUtils;
import sf.tools.StringUtils;

import java.util.List;
import java.util.Map;

public class ParaModel implements TemplateMethodModelEx {
    @Override
    public Object exec(List arguments) throws TemplateModelException {
        Environment env = Environment.getCurrentEnvironment();
        Map map = (Map) FreemarkerHelp.getRootDataModel(env);
        List<Object> list = (List<Object>) map.get(TemplateConstants.SQL_PARA_KEY);
        if (list != null && CollectionUtils.isNotEmpty(arguments)) {
            Object key = arguments.get(0);
            if (key instanceof TemplateModel) {
                Object obj = FreemarkerHelp.getUnwrap((TemplateModel) key);
                String str = obj == null ? null : String.valueOf(obj);
                if (StringUtils.isNotBlank(str)) {
                    Object value = map.get(str);
                    list.add(value);
                    return "?";
                }
            }
        }
        return "";
    }
}
